<template>
	<view class="history" style="padding-top: 80rpx;">
		<view v-if="list.length>0" style="position: fixed;z-index: 999999999;
		right: 30rpx;top: 20rpx;width: 100%;height: 60rpx;line-height: 60rpx;
		text-align: center; color: #ffffff;font-size: 28rpx;display: flex;justify-content: flex-end;">
			<view class="" @click="changeAct" style="background: #4e98dc;width: 120rpx;border-radius: 10rpx;">
				{{text}}
			</view>
		</view>
		<view class="" >
			<view class="item" v-for="(item,index) in list" :key="index">
				<view :class="['check',item.isChecked?'check-a':'']" v-if="showDel" @click.stop="changeSelect(index)">
				</view>
				<view class="" style="display: flex;width: 100%;"
					v-if="item.result.baike_info">
					<view class="img-l-box" >
						<view class="alertbox" v-if="item.alert">
							预警动物
						</view>
						<image :src="`data:image/png;base64,${item.imgurl}`" mode="aspectFill" class="img-l" :lazy-load="true"></image>
					</view>
					<view class="item-r">
						<view class="item-t">
							<view class="t-l">
								{{item.result.name}}
							</view>
							<view class="t-r">
								{{item.createTime || '-'}}
							</view>
						</view>
						<view class="item-b" @click="tobaike(item.result.name)">
							<view class="b-l">
								<view class="font1 text-truncate">
									{{item.result.baike_info.description}}
								</view>
							</view>
							<view class="b-r">

							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="nodata" v-if="list.length===0">
			<image src="/static/nodatal.png" mode="aspectFill" class="nodataimg"></image>
			<view class="">
				暂无数据~~
			</view>
		</view>
		<!-- #ifdef APP-PLUS -->
		<view class="" v-if="showDel" style="display: flex;position: fixed;bottom: 330rpx;left: 0;width: 100%;">
			<button type="plain" style="width: 180rpx;height: 60rpx;line-height: 60rpx;
			font-size: 28rpx;" @click="daochu">导出</button>
			<button type="primary" style="width: 180rpx;height: 60rpx;line-height: 60rpx;font-size: 28rpx;"
				@click="confirm">删除</button>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP -->
		<view class="" v-if="showDel" style="display: flex;position: fixed;bottom: 30rpx;left: 0;width: 100%;">
			<button type="plain" style="width: 180rpx;height: 60rpx;line-height: 60rpx;
			font-size: 28rpx;" @click="daochu">导出</button>
			<button type="primary" style="width: 180rpx;height: 60rpx;line-height: 60rpx;font-size: 28rpx;"
				@click="confirm">删除</button>
		</view>
		<!-- #endif -->
		<!-- <view class="content" ref="pdfContent" style="position: fixed;right:999999999px;top:99999999px;z-index: -1;">
			这里是PDF内容示例
		</view> -->

	</view>
</template>

<script>
	   
	import {
		exportPdf,
		animalList,
		recordAdd,
		recordList,
		recordDelete
	} from '@/api/login'
	export default {
		data() {
			return {
				isConfirm: false, //避免重复删除
				isShangchuan: false, //避免重复上传
				showDel: false,
				text: '操作',
				list: [],
				param :{
					page:1,
					limit:10
				},
				total:0,
				pull:false
			}
		},
		computed: {
			listChecked() {
				// let list = this.list.map((item => {
				// 	return item.isChecked
				// }))
				let selectedIds = []
				if(this.list.length>0){
					selectedIds =  this.list.filter(item => item.isChecked).map(item => item.id);
				}
				 return selectedIds
			},
			listCheckedIndex() {
				// let list = this.list.map((item => {
				// 	return item.isChecked
				// }))
				let selectedIds = []
				if(this.list.length>0){
					// selectedIds =  this.list.filter(item => item.isChecked).map((item) => item.id);
					this.list.forEach((item,index)=>{
						if(item.isChecked){
							selectedIds.push(index)
						}
					})
				}
				 return selectedIds
			}
		},
		onLoad() {
			// this.getList()
			this.changeText('操作')
		},
		
		onNavigationBarButtonTap(e) {
			console.log(e)
			if (e.text == '操作') {
				if (this.text == '操作') {
					this.changeText('取消')
					this.showDel = true
				} else {
					this.showDel = false
					this.changeText('操作')
				}

				let list = JSON.parse(JSON.stringify(this.list))
				list.forEach((item, ii) => {
					item['isChecked'] = false
				})
				this.list = JSON.parse(JSON.stringify(list))
			}
		},
		onShow() {
			console.log('show')
			this.param={
				page:1,
				limit:10
			}
			this.getList()
			this.changeText('操作')
		},
		onPullDownRefresh() {
			this.pull=true
			this.param.page=1
			this.getList()
		},
		onReachBottom(){
			if(this.param.page===this.total) return
			this.param.page=this.param.page+1
		
			this.getList()
		},
		methods: {

			async exportPDF() {
				const pdfContent = this.$refs.pdfContent;
				let that = this;
				uni.showLoading({
					title: '正在生成PDF'
				});
				setTimeout(function() {
					html2canvas(pdfContent, {
						dpi: 192,
						scale: 2, // 提高画质，scale越大越清晰，但导出时间会变长
						useCORS: true // 解决图片跨域问题
					}).then(canvas => {
						let contentWidth = canvas.width;
						let contentHeight = canvas.height;
						let pageHeight = contentWidth / 592.28 * 841.89;
						let leftHeight = pageHeight;
						let position = 0;
						let imgWidth = 595.28;
						let imgHeight = 592.28 / contentWidth * contentHeight;
						let pageData = canvas.toDataURL('image/jpeg', 1.0);
						let PDF = new JsPDF('', 'pt', 'a4');
						if (leftHeight < pageHeight) {
							PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
						} else {
							while (leftHeight > 0) {
								PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
								leftHeight -= pageHeight;
								position -= 841.89;
								if (leftHeight > 0) {
									PDF.addPage();
								}
							}
						}
						PDF.save('download.pdf');
						uni.hideLoading();
					}, function(err) {
						console.error(err);
						uni.hideLoading();
					});
				}, 100);
			},
			changeAct() {
				if (this.text == '操作') {
					this.changeText('取消')
					this.showDel = true
				} else {
					this.showDel = false
					this.changeText('操作')
				}

				let list = JSON.parse(JSON.stringify(this.list))
				list.forEach((item, ii) => {
					item['isChecked'] = false
				})

				this.list = JSON.parse(JSON.stringify(list))
			},
			daochu() {
				let list = JSON.parse(JSON.stringify(this.list))
				let list2 =list.filter(item=>{return item.isChecked})
				if(list2.length===0) {
					uni.showToast({
						icon:'none',
						title:'请选择导出内容'
					})
					return
				}
				
				uni.showLoading({
					title:'导出PDF进行中...'
				})
				let list3 = list2.map((item)=>{
					let param = {
						"check_time": item.createTime,
						"name":item.result.name || '',
						"detail": item.result.baike_info.description,
						url:item.result.baike_info.image_url,
						alert:''
					}
					if(item.alert){
						param['alert']='预警'
					}
					return param
				})
				exportPdf(list3).then(res => {
					this.showDel = false
					this.isConfirm = false
					this.showDel = false
					let fileName = res.data.substring(res.data.lastIndexOf('/') + 1)
					console.log('导出 fileName filePath ',res.data,fileName, wx.env.USER_DATA_PATH + '/' + fileName)
					uni.downloadFile({
						url: 'https://nchc.vicp.cc/'+res.data, //文件地址
						filePath: wx.env.USER_DATA_PATH + '/' + fileName,
						success: function(res) {
							let statusCode = res.statusCode
							let tempFIlePath = res.filePath || res.tempFilePath
							console.log('statusCode,tempFIlePath',statusCode,tempFIlePath,res);
							console.log('res01111',res)
							const filePath = res.filePath || res.tempFilePath;
							uni.openDocument({
								filePath: filePath,
								showMenu: true,
								success: function(res) {}
							});
							uni.hideLoading()
							uni.showToast({
								icon:'none',
								title:'导出成功'
							})
							
						},
						fail:(err)=> {
							console.log('err222',err)
							uni.showToast({
								icon:'none',
								title:'导出失败'
							})
						}
					})
					
				}).catch(msg => {
					this.showDel = false
					this.isConfirm = false
					this.showDel = false
					console.log('上传导出',msg)
				})
			},
			getList() {
				recordList(this.param).then(res => {
					console.log('res',res)
					this.total = Math.ceil(res.count/this.param.limit)
					let list2 = res.data.filter(item=>{
						console.log('item',item)
						return item.target!=='非动物'
					})
					let list3=res.data.filter(item=>{return item.target==='非动物'}).map(item=>{return item.id})
					console.log('list2',list2,list3);
					// this.doConfirm(JSON.stringify(list3))
					let list = list2.map(item=>{
						let content = JSON.parse(item.content)
						let result = content
						return {
							alert:item.alert==='True',
							createTime:item.create_time,
							imgurl: item.pic,
							isChecked:false,
							result:result,
							id:item.id
						}
					})
					console.log(2222222222, list)
					if(this.param.page===1){
						this.list = list;
						console.log(2222222222, list);
						this.$forceUpdate()
					}else{
						this.list = this.list.concat(list)
						this.$forceUpdate()
					}
					// console.log('list2222',this.list,this.param.page,list)
					if(this.pull){
						uni.stopPullDownRefresh()
					}
				}).catch(msg => {
					console.log('listerr', msg)
					if(this.pull){
						uni.stopPullDownRefresh()
					}
				})
			},
			
			changeText(text) {
				this.text = text
				// 已渲染
				var pages = getCurrentPages();
				var page = pages[pages.length - 1];

				// #ifdef H5
				document.querySelector('.uni-page-head-ft .uni-page-head-btn .uni-btn-icon').innerHTML = text;
				// #endif

				// #ifdef APP-PLUS
				var currentVebview = page.$getAppWebview();
				var tn = currentVebview.getStyle().titleNView;
				tn.buttons[0].text = text; // \ue... 字体图标
				currentVebview.setStyle({
					// titleNView: tn
					titleNView: ''
				})
				// #endif
			},
			tobaike(name) {
				if (this.showDel) return
				uni.navigateTo({
					url: '/pages/baike/index?name=' + name
				})
			},
			changeSelect(index) {
				let list = JSON.parse(JSON.stringify(this.list))
				list.forEach((item, ii) => {
					if (ii === index) {
						item['isChecked'] = !item['isChecked']
					}
				})
				this.list = JSON.parse(JSON.stringify(list))
			},
			cancel() {
				this.showDel = false
			},
			confirm() {
				if(this.listChecked.length===0){
					uni.showToast({
						title:'请先选择',
						icon:'none'
					})
					return
				}
				if (this.isConfirm) {
					return
				}
				this.isConfirm = true
				let that = this
				uni.showModal({
					title: '提示',
					content: '确定删除吗？',
					success: function(res) {
						if (res.confirm) {
							that.doConfirm(JSON.stringify(that.listChecked))
							console.log('that.listChecked',that.listChecked)
							// uni.setStorageSync('historyList', list2)
						
						} else if (res.cancel) {
							that.isConfirm = false
						}
					}
				});
			},
			doConfirm(idlist){
				let that =this
				let list = JSON.parse(JSON.stringify(this.list))
				recordDelete(idlist).then(res => {
					console.log('删除',res)
					// this.getList()
					// this.listCheckedIndex.forEach((item)=>{
					// 	list.splice(item,1)
					// })
					for (let i = 0; i < this.listCheckedIndex.length; i++) {
						let key = this.listCheckedIndex[i]-i
						list.splice(key,1)
					}
					this.list =JSON.parse(JSON.stringify(list))
					that.showDel = false
					that.isConfirm = false
					that.showDel = false
					that.changeText('操作')
				}).catch(msg => {
					console.log('listerr', msg)
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.history {
		padding: 0 30rpx;
		box-sizing: border-box;

		.nodata {
			margin-top: 80rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: 26rpx;
			text-align: center;
			color: #666;

			.nodataimg {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 16rpx;
			}
		}

		.item {
			width: 100%;
			display: flex;
			padding: 30rpx 0;
			border-bottom: 1rpx solid #ececec;

			.img-l-box {
				width: 200rpx;
				height: 200rpx;
				margin-right: 20rpx;
				flex: none;
				position: relative;
			}
			.alertbox{
				position: absolute;
				left: 0;
				top: 0;
				width: 200rpx;
				height: 58rpx;
				line-height: 58rpx;
				text-align: center;
				background-color: #e65538;
				color: #ffffff;
				font-size: 28rpx;
				text-align: center;
			}
			.img-l {
				width: 200rpx;
				height: 200rpx;
			}
			.item-r {
				flex: auto;
				height: 200rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.item-t {
					display: flex;
					justify-content: space-between;

					.t-l {
						font-size: 30rpx;
						font-weight: bold;

					}

					.t-r {
						font-size: 26rpx;
						color: #666666;
					}
				}

				.item-b {
					height: 120rpx;
					line-height: 40rpx;
					display: flex;
					align-items: center;
					color: #666;
				}

				.font1 {
					height: 120rpx;
					margin-right: 20rpx;
					font-size: 28rpx;
					letter-spacing: 2rpx;
					word-break: break-all;

				}

				.b-l {
					box-sizing: border-box;
					padding-right: 20rpx;
					flex: auto;
				}

				.b-r {
					width: 16rpx;
					height: 16rpx;
					border: 1rpx solid #999;
					transform: rotate(45deg);
					border-bottom: 0;
					border-left: 0;
					flex: none;
				}
			}
		}
	}

	.text-truncate {
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: normal;
		width: 100%;
	}

	.check {
		width: 56rpx;
		height: 56rpx;
		border-radius: 100%;
		flex: none;
		align-self: center;
		margin-right: 24rpx;
		background-color: #ffffff;
		border: 4rpx solid #999;
		box-sizing: border-box;
	}

	.check-a {
		background: url(@/static/radio.png) no-repeat center;
		background-size: 60rpx 60rpx;
		border: 0;
	}
</style>